package com.hmall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;

import java.util.HashSet;

@Configuration
public class GatewayConfiguration {

    //*规则初始化，支持路由规则和API规则，这里仅演示路由规则
    @PostConstruct
    public void doInit(){
        initGatewayRules();

        BlockRequestHandler blockRequestHandler = (exchange,t) -> ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue("请求次数太快了，请稍后再试！");
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    //初始化规则
    private void initGatewayRules(){
        HashSet<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("item")
                .setGrade(RuleConstant.FLOW_GRADE_QPS)
                .setCount(2)
                .setIntervalSec(1)
                .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT));

        rules.add(new GatewayFlowRule("cart")
                .setCount(1)
                .setIntervalSec(1)
                .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT));
        GatewayRuleManager.loadRules(rules);
    }
}
